<!-- 这是聊天界面 -->
<template>
	<view style="display: flex;flex-direction: column;height: 100vh;overflow: hidden;">
		<view class="nav" style="margin-top: 13px;">
			<uniNavBar height="65px" left-icon="left" background-color='#FFF' :title="chatname" @clickLeft="backto"
				class="setonl" :border="false" />
		</view>

		<view class="lodingv" v-if="Isloding">加载中...</view>
		<scroll-view class="chatcon" id="chatconsd" ref="myScrollView" :scroll-top="scrollTop" scroll-y='true'
			@scrolltoupper="loadchat" @scroll="scroll" scroll-with-animation>
			<view class="lodingv" v-if="nomessage">没有更多数据了</view>
			<view class="chatcon-every" v-for="(item,index) in Chathistory">
				<view class="me" v-if="item.sender_id==chatText.sender_id">
					<image :src="mycanva" mode="aspectFill"></image>
					<view class="bubble">{{item.content}}</view>

				</view>
				<view class="other" v-if="item.sender_id!=chatText.sender_id">
					<image :src="avaerimg" mode="aspectFill"></image>
					<view class="bubble">{{item.content}}</view>
				</view>
			</view>
		</scroll-view>
		<view class="send-container">
			<textarea class="uni-input" auto-height confirm-type="send" v-model="chatText.content" />
			<uni-transition ref="ani" custom-class="transition" :mode-class="modeClass" :styles="styles" :show="show">
				<button class="send" @click="insertChatRow">发送</button>
			</uni-transition>
		</view>
	</view>
</template>
<script>
	import Sqlite from '@/utils/sqlex.js'
	import websocketManager from '@/websocketService.js'
	import Dataprocessing from '@/utils/Dataprocessing.js'
	import uniNavBar from '@/uni_modules/uni-nav-bar/components/uni-nav-bar/uni-nav-bar.vue'
	export default {
		components: {
			uniNavBar
		},
		data() {
			return {
				mycanva:this.$store.state.imageurl,
				nomessage: false,
				Isloding: false,
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				// 聊天记录数组
				Chathistory: [],
				page: 1,
				pageSize: 10,
				sourceIsInfo: '',
				addmessage: {},
				chatname: '',
				avaerimg: '',
				chatList: this.$store.state.chatList,
				show: false,
				systemBarHeight: 0,
				back: require('@/static/backclazk.png'),
				dbName: '',
				dbPath: '_doc/dianji_chat.db',
				dbTable: '',
				dbIsOpen: false,
				chatText: {
					message_id: '',
					sender_id: this.$store.state.id,
					content: '',
					receiver_id: '',
					timestamp: '',
				},
				styles: '',
				modeClass: ['fade', 'slide-right'],
			}
		},
		created() {
			this.getSysteminfo();
		},
		onLoad(options) {

			uni.onKeyboardHeightChange(res => {
				if (res.height) {
					this.goTop()
				} else {}
			});
			this.sourceIsInfo = options.sourceIsInfo
			// 如果是从个人信息跳转到消息聊天界面
			if (options.sourceIsInfo == '1') {
				this.chatname = options.name
				this.avaerimg = options.image
				this.dbTable = `message_${options.Id}`
				this.dbName = `sqlchat_${this.$store.state.id}`
				this.chatText.receiver_id = options.Id
			} else {
				// 如果是从消息列表跳转进来的
				this.chatname = this.$store.state.chatItem.username
				this.avaerimg = this.$store.state.chatItem.receiver_avatarBase
				this.dbTable = `message_${this.$store.state.chatItem.receiver_id}`
				this.dbName = `sqlchat_${this.$store.state.id}`
				this.chatText.receiver_id = this.$store.state.chatItem.receiver_id
			}
			this.getChathistory() //获取聊天记录
			this.cleanmessnum()
			this.styles = {
				justifyContent: 'center',
				alignItems: 'center',
				height: '2rem',
				textAlign: 'center',
			}
		},
		mounted() {
			this.scrollTop = 9999999999999
		},
		watch: {
			// 同时监听 firstName 和 lastName
			fullName(newVal) {
				if (newVal.length > 0) {
					this.show = true
				} else {
					this.show = false
				}
			},
			nowchagemess(newValue, oldValue) {
				// 判断这个信息是否是当前聊天的角色
				if (this.chatText.receiver_id == newValue.sender_id) {
					this.Chathistory.push(newValue)
					this.goTop()
					this.cleanmessnum()
				}

			}
		},
		computed: {
			fullName() {
				return this.chatText.content;
			},
			nowchagemess() {
				return this.$store.state.nowchagemess
			}
		},
		// onShow() {
		// 	this.goTop()
		// 	this.getChathistory() //获取聊天记录
		// },
		methods: {
			cleanmessnum() {
				const foundObject = this.$store.state.chatList.find(item => item.receiver_id == this.chatText.receiver_id);
				if (foundObject.islook !== 'yse') {
					let message = Number(this.$store.state.messagenum) - Number(foundObject.islook)
					this.$store.commit('setmessagenum', message);
					if (message == 0) {
						uni.removeTabBarBadge({
							index: 1 // 这里的index要和之前设置角标时的索引保持一致，用于指定要移除角标的tabBar
						});
					} else {
						uni.setTabBarBadge({ //显示数字
							index: 1, //tabbar下标
							text: message > 99 ? '99+' : `${message}` //数字
						})
					}
				}
				let update_sql = `UPDATE chat_list SET islook = 'yse' WHERE receiver_id = ${this.chatText.receiver_id}`
				Sqlite.addOrUpdateChatData(this.dbName, update_sql)
			},
			scroll: function(e) {
				this.old.scrollTop = e.detail.scrollTop
			},
			goTop: function(e) {
				// 解决view层不同步的问题
				this.scrollTop = this.old.scrollTop
				this.$nextTick(function() {
					this.scrollTop = 999999
				});
			},
			loadchat() {
				if (!this.nomessage) {
					this.Isloding = true
					this.getChathistory().then((e) => {
						this.Isloding = false
						console.log("加载完成")
					})
				}
			},
			// 图片存储
			async fetchImageAsBase64(url) {
				return new Promise((resolve, reject) => {
					try {
						uni.request({
							url: url,
							responseType: 'arraybuffer', // 设置响应类型为arraybuffer，方便后续处理成Base64
							success: (res) => {
								const base64 = uni.arrayBufferToBase64(res.data);
								const urlyiu = 'data:image/jpeg;base64,' +
									base64; // 这里假设图片是jpeg格式，根据实际情况修改
								resolve(urlyiu);
							},
							fail: (err) => {
								console.log('获取图片失败', err);
								reject(err);
							}
						});
					} catch (error) {
						console.error('Error fetching or processing image:', error);
						reject(error);
					}
				});
			},
			// 获取当前用户的全部聊天记录
			async getChathistory() {
				let len = this.Chathistory.length
				let sql = `SELECT * FROM ${this.dbTable} ORDER BY timestamp DESC LIMIT 14 OFFSET ${len};`
				return new Promise((resolve, reject) => {
					plus.sqlite.selectSql({
						name: this.dbName,
						sql: sql,
						success: (e) => {
							if (e.length == 0) {
								this.nomessage = true
							}
							console.log(e)
							let arr = e.reverse();
							this.Chathistory.unshift(...arr)
							resolve();
						},
						fail(e) {
							console.log('查询失败')
						}
					})
				})
			},

			getSysteminfo() {
				uni.getSystemInfo({
					success: res => {
						this.systemBarHeight = res.statusBarHeight;
					}
				});
			},
			backto() {
				uni.navigateBack({
					delta: 1
				})
			},
			// async open(){
			// 	let odb=await Sqlite.openSqlite();
			// 	this.odb=odb;
			// },
			// 创建表
			async createChatTable() {
				// 创建表
				let sql = 'CREATE TABLE if not exists ' + this.dbTable +
					' ( "message_id" varchar(32) NOT NULL,"content" varchar(1024),"sender_id" varchar(32), "receiver_id" varchar(32), "timestamp" varchar(32), PRIMARY KEY ("message_id"));'
				this.executeSql(sql)
			},
			// 新增数据
			insertChatRow() {
				if (this.chatText.content == '') {
					console.log("不能发送空白信息")
				} else {
					// 组合成 SQLite 需要的格式
					let suij = Math.floor(10000 + Math.random() * 90000)
					const timestampMs = Date.now();
					const timestampSec = Math.floor(timestampMs / 1000);
					this.chatText.message_id = timestampSec + this.chatText.sender_id + suij
					this.chatText.timestamp=this.getCurrentFormattedDateTime()
					let data = this.chatText
					data.id++
					let sql = "insert into " + this.dbTable + " values('" + data.message_id + "','" + data.content +
						"','" + data.sender_id + "','" + data.receiver_id + "','" + data.timestamp + "')";
					this.createChatTable().then((e) => {
						this.executeSql(sql).then((e) => {
							let pushchat = {
								content: data.content,
								message_id: data.message_id,
								receiver_id: data.receiver_id,
								sender_id: data.sender_id,
								timestamp: data.timestamp
							}
							this.Chathistory.push(pushchat)
						})
						this.addchatlist(data)
					})

				}
				// 上面为发送消息时数据库添加模拟，下面为用户AB消息发送通讯模拟
				let message = {
					sender_id: `${this.$store.state.id}`,
					receiver_id: this.chatText.receiver_id,
					receiver_avatarBase: this.$store.state.imageurl,
					endmessge: this.chatText.content,
					username: this.$store.state.username,
					endmessgetime: this.chatText.timestamp,
					islook: "no",
					type: 'message'
				}
				console.log("发送信息")
				websocketManager.send(message)
			},
			getCurrentFormattedDateTime() {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始计数，需加1并补0格式化
				const day = String(now.getDate()).padStart(2, '0');
				const hours = String(now.getHours()).padStart(2, '0');
				const minutes = String(now.getMinutes()).padStart(2, '0');
				const seconds = String(now.getSeconds()).padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			// 添加或更新数据到 chat_list 表
			async addchatlist(data) {
				const receiverAvatarBase64 = this.sourceIsInfo == '1' ? await this.fetchImageAsBase64(this.avaerimg) :
					this.avaerimg;
				const newData = {
					receiver_id: data.receiver_id, //接收id
					receiver_avatarBase: receiverAvatarBase64, // Base64 编码的图片数据
					endmessge: data.content, //信息内容
					sqlname: this.dbTable, //数据库名称
					username: this.chatname, //用户名称
					endmessgetime: data.timestamp
				};
				let sql = "insert or replace into " + 'chat_list' + " values('" + newData.receiver_id + "','" + newData
					.receiver_avatarBase +
					"','" + newData.endmessge + "','" + newData.sqlname + "','" + newData.username + "','" + newData
					.endmessgetime + "','yse')";
				Sqlite.addOrUpdateChatData(this.dbName, sql).then((e) => {
					this.chatText.content = ''
				})
			},
			// 查询数据
			selectSql() {
				let curPage = 1
				let pageSize = 20
				let fromId = this.chatText.sender_id
				// let sql = 'select * from ' + this.dbTable + ' where sender_id=' + fromId +
				// 	' limit ' + pageSize + ' offset ' + (curPage - 1) * pageSize;

				let sql = `select * from ${this.dbTable}`
				this.executeSql(sql)
			},
			async executeSql(sql) {
				plus.sqlite.selectSql({
					name: this.dbName,
					sql: sql,
					success: function(data) {
						console.log(data, '---------------')
					},
					fail: function(e) {
						console.log('selectSql failed: ' + JSON.stringify(e));
					}
				});
			},
			scheduleCheck() {
				console.log("判断token是否使用")
			}
		}
	}
</script>
<style scoped lang="scss">
	.lodingv {
		background-color: #ededed;
		font-size: 14px;
		display: flex;
		justify-content: center;
	}

	.chatcon {
		background-color: #ededed;
		// height: 400px;
		flex: 1;
		overflow: hidden;

		.chatcon-every {
			padding: 7px 0;
			min-height: 45px;

			.me {
				width: 100%;
				display: flex;
				justify-content: flex-start;
				flex-direction: row-reverse;

				image {
					border-radius: 6px;
					margin: 0 10px;
					width: 35px;
					height: 35px;
				}

				.bubble {
					max-width: 70%;
					background-color: #37a7ff;
					padding: 6px;
					border-radius: 4px;
					color: #FFF;
					font-size: 15px;
				}
			}

			.other {
				width: 100%;
				display: flex;
				justify-content: flex-start;

				image {
					border-radius: 6px;
					margin: 0 10px;
					width: 35px;
					height: 35px
				}

				.bubble {
					max-width: 70%;
					background-color: #ffffff;
					padding: 6px;
					border-radius: 4px;
					font-size: 15px;
					color: #000;
				}
			}
		}
	}

	.nav {
		// background-color: #cecece;
		width: 100vw;
		background-color: rgba(206, 206, 206, 0.14);

		.back {
			z-index: 999;
			position: fixed;
			height: 3rem;
			width: 100vw;
			display: flex;
			align-items: center;

			.imgcon {
				width: 1.5rem;
				height: 1.5rem;
			}

			img {
				margin-left: 0.5rem;
				width: 1.5rem;
				height: 1.5rem;
			}
		}
	}

	.send-container {
		padding: 6px 0;
		// padding: 0.5rem 1rem 0.5rem 1rem;
		min-height: 3rem;
		background-color: #FFF;
		border: 1px solid #dcdcdc;
		display: flex;
		align-items: center;
		width: 100vw;
		background-color: #f7f7f7;

		.uni-input {
			margin-left: 10px;
			padding: 0.4rem 1rem;
			border-radius: 8px;
			background-color: #ffffff;
		}

		.send {
			margin: 0 12px;
			background-color: #1b497d;
			color: #FFF;
			height: 2rem;
			width: 61px;
			font-size: 1rem;
			display: flex;
			align-items: center;
			justify-content: center;

		}
	}
</style>